package user_mgt

import (
	"fmt"
	"net/http"
)

// NewEmployeeMiddlewares 获取处理员工请求的中间件接口实例
func NewEmployeeMiddlewares() Middlewares {
	return &EmployeeImpl{}
}

// NewAdminMiddlewares 获取处理管理员请求的中间件接口实例
func NewAdminMiddlewares() Middlewares {
	return &AdminImpl{}
}

// AuthMiddleware 员工客户端请求的身份验证中间件
func (*EmployeeImpl) AuthMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 检查logger是否为空
		if logger == nil {
			fmt.Println("logger is nil")
			http.Error(w, "logger is nil", http.StatusInternalServerError)
			return
		}

		//获取前端传来的Cookie
		cookies := r.Cookies()
		//在此cookies中获取到sessionID
		token, err := getTokenByCookies(cookies)
		if err != nil {
			logger.Errorf("getTokenByCookies failed, err:%v", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// 检查token是否为空
		if token == "" {
			logger.Error("token is empty")
			http.Error(w, "token is empty", http.StatusInternalServerError)
			return
		}

		//验证token
		isToken, err := jwtEmployee.ParseAndVerifyToken(token)
		if err != nil {
			logger.Error("verify token failed: ", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		if !isToken {
			logger.Error("token is not valid", err)
			http.Error(w, "token is not valid", http.StatusInternalServerError)
			return
		}

		// 获取id
		employId, err := jwtEmployee.GetIdFromToken(token)
		if err != nil {
			logger.Errorf("GetIdFromToken failed, err:%v", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		//将id传入上下文
		ctx, err := setToContext("employeeId", employId, r.Context())
		if err != nil {
			logger.Errorf("setToContext failed, err:%v", err)
			http.Error(w, "Unauthorized", http.StatusInternalServerError)
			return
		}

		// 调用下一个处理程序
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

// AuthMiddleware 管理员客户端请求的身份验证中间件
func (*AdminImpl) AuthMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 检查logger是否为空
		if logger == nil {
			fmt.Println("logger is nil")
			http.Error(w, "logger is nil", http.StatusInternalServerError)
			return
		}

		//获取前端传来的Cookie
		cookies := r.Cookies()
		//在此cookies中获取到sessionID
		token, err := getTokenByCookies(cookies)
		if err != nil {
			logger.Errorf("getTokenByCookies failed, err:%v", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// 检查token是否为空
		if token == "" {
			logger.Error("token is empty")
			http.Error(w, "token is empty", http.StatusInternalServerError)
			return
		}

		//验证token
		isToken, err := jwtAdmin.ParseAndVerifyToken(token)
		if err != nil {
			logger.Error("verify token failed: ", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		if !isToken {
			logger.Error("token is not valid", err)
			http.Error(w, "token is not valid", http.StatusInternalServerError)
			return
		}

		// 获取id
		adminId, err := jwtAdmin.GetIdFromToken(token)
		if err != nil {
			logger.Errorf("GetIdFromToken failed, err:%v", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		//将id传入上下文
		ctx, err := setToContext("adminId", adminId, r.Context())
		if err != nil {
			logger.Errorf("setToContext failed, err:%v", err)
			http.Error(w, "Unauthorized", http.StatusInternalServerError)
			return
		}

		// 调用下一个处理程序
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

// CorsMiddleware 解决跨域问题
func (*EmployeeImpl) CorsMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 获取请求的 Origin
		origin := r.Header.Get("Origin")

		// 动态设置允许跨域的 Origin
		if origin != "" {
			w.Header().Set("Access-Control-Allow-Origin", origin)
		}

		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
		w.Header().Set("Access-Control-Allow-Credentials", "true")
		w.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")

		// 处理 OPTIONS 请求
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusNoContent)
			return
		}

		next.ServeHTTP(w, r)
	})
}

// CorsMiddleware 解决跨域问题
func (*AdminImpl) CorsMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 获取请求的 Origin
		origin := r.Header.Get("Origin")

		// 动态设置允许跨域的 Origin
		if origin != "" {
			w.Header().Set("Access-Control-Allow-Origin", origin)
		}

		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
		w.Header().Set("Access-Control-Allow-Credentials", "true")
		w.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")

		// 处理 OPTIONS 请求
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusNoContent)
			return
		}

		next.ServeHTTP(w, r)
	})
}

// PostOnlyMiddleware 只允许 POST 请求
func (*EmployeeImpl) PostOnlyMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "POST" {
			http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
			return
		}
		next.ServeHTTP(w, r)
	})
}

// PostOnlyMiddleware 只允许 POST 请求
func (*AdminImpl) PostOnlyMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "POST" {
			http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
			return
		}
		next.ServeHTTP(w, r)
	})
}

// GetOnlyMiddleware 只允许 GET 请求
func (*EmployeeImpl) GetOnlyMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "GET" {
			http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
			return
		}
		next.ServeHTTP(w, r)
	})
}
